#!/bin/bash
# ----------------------------------------------------------------
#   1-CreateDirecotryStructure.sh: Create the directory structure
#   	and relocate each files to the right place
#
#	Usage:
#		1-CreateDirectoryStructure.sh dataDir directoryStructure
#   initializes the Adaptation fMRI experiment. This experiment 
#   effect of stimulus history on the current evoked response,
#   on serial position -1 to -N are manipulated in a 
#
#
#   Inputs
#   -------
#   [protocolListFileName]: path to a file that should contain a
#   	description of the protocols to be used. If nothing is
#   	the file ./Config/ProtocolList.cfg will be used
#
#
#   Outputs
#   -------
#   ./Data/[expType]/[protocol]/[subjID]/[subjID]-[protocol]-
#  	this file will store all experimental info, experiment
#   	parameters, stimuli used, and data collected
#
#   Examples
#   -------
#    i) AdaptID_v1_1('./protocols.txt')
#   ii) AdaptID_v1_1
#
# ----------------------------------------------------------------
# ``Redistribution and use, with or without modification, are
#	permitted provided that the list of contributors below is
#	preserved.``
#
#   Original code by Marcelo G Mattar (09/04/2012)
#	mattar@sas.upenn.edu
# ----------------------------------------------------------------


# --- Check input command ---
if [ $# -ne 2 ]; then
cat << EOF
USAGE: `basename $0` dataDir directoryStructure
EOF
	exit 1
fi

# --- Read input parameters ---
dataDir=$1
directoryStructure=$2

# --- Keep a copy of calling directory, so that relative pathnames are properly used
OCD=$PWD

# --- Read directory structure from external file
. $directoryStructure


# -----------------------------------------------------
# 1) --- CONVERT FILES TO NIFTI ---
# -----------------------------------------------------

# Convert DICOM to nifti
/usr/local/mricron-64bit/dcm2nii $dataDir/00*


# -----------------------------------------------------
# 2) --- MOVE FILES AROUND ---
# -----------------------------------------------------


countDir=1
for thisDir in ${dataDir}/00*
do
	echo "Working on $thisDir, type ${scanType[$countDir]} and name ${scanName[$countDir]}"
	baseDir=${dataDir}/${scanType[$countDir]}
	fileName=${baseDir}/${scanName[$countDir]}.nii.gz
	subDir=${baseDir}/raw/${scanName[$countDir]}

	if [ ! -d "$baseDir" ]; then
		mkdir $baseDir
	fi
	if [ ! -d "${baseDir}/raw" ]; then
		mkdir ${baseDir}/raw
	fi
	if [ ! -d "$subDir" ]; then
		mkdir $subDir
	fi

	# Move all .nii.gz files to its respective directory
	countFile=1
	for thisFile in ${thisDir}/*.nii.gz
	do
		if [ $countFile -gt 1 ]; then
			mv $thisFile ${fileName/.nii.gz/}${countFile}.nii.gz
		else
			mv $thisFile $fileName
		fi
		((countFile++))
	done

	# Move all raw files to the raw/ directory
	mv ${thisDir}/* $subDir

	# Remove the original directory
	rmdir ${thisDir}

	((countDir++))
done









cd $OCD

exit 0
